<?php
/**
 * @author spenceryg
 * @date 2022/4/14
 * @time 10:38 上午
 * @focus love & life
 */


namespace app\common\lib\verify;


use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use app\common\lib\verify\interfaces\Verify;
use Darabonba\OpenApi\Models\Config;
use GuzzleHttp\Exception\ClientException;

class AliSmsVerify implements Verify
{

    protected $client = null;
    protected $template = null;


    public function sendCode(string $to, $code)
    {
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $to,
            "signName" => config('sms.ali_sms.template.' . $this->template . '.SignName'),
            "templateCode" => config('sms.ali_sms.template.' . $this->template . '.TemplateCode'),
            "templateParam" => json_encode(is_array($code) ? $code : ['code' => $code])
        ]);
        // 复制代码运行请自行打印 API 的返回值
        try{
            $res = $this->client->sendSms($sendSmsRequest);
            if ($res->body->code != 'OK'){
                throw new \Exception($res->body->message);
            }
        }catch (ClientException $e) {
            throw new \Exception($e->getMessage());
        }
        catch (TeaUnableRetryError $e){
            throw new \Exception($e->getMessage());
        }

    }

    public function __construct($template = 'default')
    {
        $config = new Config([
            "accessKeyId" => config('sms.ali_sms.accessKeyId'),
            "accessKeySecret" => config('sms.ali_sms.accessKeySecret')
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        $this->client = new Dysmsapi($config);
        $this->template = $template;
    }



}
